<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
class Index extends Controller
{
    public function index()
    {
        if (!session("uid")){
            $this->error("请登录","/admin/index/login");
        }

        //列出登录用户拥有的权限
        $groupId = Db::name("auth_group_user")->where("uid",session("uid"))->value("group_id");
        $ruleIdList = Db::name("auth_group_rule")->where("group_id",$groupId)->column("rule_id");
        $ruleList = array();
        foreach ($ruleIdList as $key => $item){
            $where["id"] = $item;
            $where["type"] = 0; //去除请求操作权限，例如图片上传请求，插件停用请求等操作请求。
            $ruleItem = Db::name("auth_rule")->where($where)->find();
            $ruleList[$ruleItem["pid"]][] = $ruleItem;
        }

        if (empty($ruleIdList)){
            $this->error("没有访问权限！","/");
        }
      
        $userInfo = Db::name("user")->where("uid",session("uid"))->field("uid,username,mobile,email,avatar")->find();
        $this->assign("ruleList",$ruleList);
        $this->assign("userInfo",$userInfo);
        return view('/index');
    }

    public function login()
    {
        if (request()->isPost()){
            $data = input("post.");
            $validate = validate("User");
            if (!$validate->scene("login")->check($data)){
                return json(["code" => 0,"msg" => $validate->getError()]);
            }
            $data["password"] = md5($data["password"]);
            $userInfo = Db::name("user")->field("password",true)->where($data)->find();
            if ($userInfo){
                if ($userInfo["status"] != 0){
                    return json(["code" => 0,"msg" => "该用户已被禁止使用"]);
                }
                session("uid",$userInfo["uid"]);
                return json(["code" => 1,"msg" =>"登录成功","data" => $userInfo]);
            }else{
                return json(["code" => 0 ,"msg" => "用户名或密码错误"]);
            }
        }else{
            return $this->fetch("/login");
        }
    }
}